import { Request, Response, NextFunction } from 'express';
import { prisma } from '@src/common/database';
import { UserRole, MemberLevel } from '@prisma/client';

// 扩展 Request 类型以包含用户信息
declare global {
  namespace Express {
    interface Request {
      user?: {
        id: bigint;
        loginId: string;
        email: string;
        role: UserRole;
        name?: string | null;
        nickname?: string | null;
        status: string;
        memberLevel: MemberLevel;
      };
    }
  }
}

const SESSION_COOKIE = 'sid';

/**
 * 从 cookie 获取当前用户信息的中间件
 * 如果用户已登录，将用户信息注入到 req.user
 * 如果未登录或会话过期，req.user 为 undefined
 */
export async function getCurrentUser(req: Request, res: Response, next: NextFunction) {
  try {
    const sid = req.cookies?.[SESSION_COOKIE];
    if (!sid) {
      req.user = undefined;
      return next();
    }

    const session = await prisma.userSession.findUnique({
      where: { id: BigInt(sid) },
      include: {
        user: {
          select: {
            id: true,
            loginId: true,
            email: true,
            role: true,
            name: true,
            nickname: true,
            status: true,
            memberLevel: true,
          },
        },
      },
    });

    if (!session || new Date(session.expiredAt) < new Date()) {
      req.user = undefined;
      return next();
    }

    req.user = {
      id: session.user.id,
      loginId: session.user.loginId,
      email: session.user.email,
      role: session.user.role,
      name: session.user.name,
      nickname: session.user.nickname,
      status: session.user.status,
      memberLevel: session.user.memberLevel,
    };

    next();
  } catch (error) {
    console.error('getCurrentUser middleware error:', error);
    req.user = undefined;
    next();
  }
}

/**
 * 要求用户已登录的中间件
 */
export function requireAuth(req: Request, res: Response, next: NextFunction) {
  if (!req.user) {
    return res.status(401).json({ error: '먼저 로그인하십시오' });
  }
  next();
}

/**
 * 要求用户为管理员的中间件
 */
export function requireAdmin(req: Request, res: Response, next: NextFunction) {
  if (!req.user) {
    return res.status(401).json({ error: '먼저 로그인하십시오' });
  }
  if (req.user.role !== UserRole.admin) {
    return res.status(403).json({ error: '需要管理员权限' });
  }
  next();
}

/**
 * 要求用户为合作伙伴的中间件
 */
export function requirePartner(req: Request, res: Response, next: NextFunction) {
  if (!req.user) {
    return res.status(401).json({ error: '먼저 로그인하십시오' });
  }
  if (req.user.role !== UserRole.partner) {
    return res.status(403).json({ error: '需要合作伙伴权限' });
  }
  next();
}

/**
 * 要求用户为管理员或合作伙伴的中间件
 */
export function requireAdminOrPartner(req: Request, res: Response, next: NextFunction) {
  if (!req.user) {
    return res.status(401).json({ error: '먼저 로그인하십시오' });
  }
  if (req.user.role !== UserRole.admin && req.user.role !== UserRole.partner) {
    return res.status(403).json({ error: '需要管理员或合作伙伴权限' });
  }
  next();
}

/**
 * 检查用户状态是否为活跃的中间件
 */
export function requireActiveUser(req: Request, res: Response, next: NextFunction) {
  if (!req.user) {
    return res.status(401).json({ error: '먼저 로그인하십시오' });
  }
  if (req.user.status !== 'active') {
    return res.status(403).json({ error: '账户已被禁用' });
  }
  next();
}
